import { NIcon } from 'naive-ui'
import { h } from 'vue'

// 渲染图标
export const renderIcon = (icon: Component) => {
  return () => {
    return h(NIcon, null, {
      default: () => h(icon)
    })
  }
}

/**
 * 16进制颜色转rgba
 * @param hex 16进制颜色
 * @param opacity 透明度
 * @returns rgba颜色
 */
export const hexToRgba = (hex: string, opacity: number) => {
  if (!hex) hex = '#ededed'
  let rgbastr = ''
  if (hex.length === 4) {
    const str = hex.split('')
    rgbastr += '#' + str[1] + str[1] + str[2] + str[2] + str[3] + str[3]
    hex = rgbastr
  }
  const rgba =
    'rgba(' +
    parseInt('0x' + hex.slice(1, 3)) +
    ',' +
    parseInt('0x' + hex.slice(3, 5)) +
    ',' +
    parseInt('0x' + hex.slice(5, 7)) +
    ',' +
    (opacity || '1') +
    ')'
  return rgba
}

export const isObject = (obj: any) => {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

/**
 * 用于将两个对象合并
 * @param obj1 接收合并对象
 * @param obj2 被合并对象
 * @returns 合并后的对象
 */
export const mergeObject = (obj1: Record<string, any>, obj2: Record<string, any>) => {
  for (const key in obj2) {
    if (isObject(obj2[key])) {
      obj1[key] = mergeObject(obj1[key], obj2[key])
    } else {
      obj1[key] = obj2[key]
    }
  }
  return obj1
}

/**
 * echart图表字体自适应
 * @param size 字体大小
 * @param screenWidth 设计稿宽度
 * @returns 转行后的字体大小
 */
export function fontSizeRem(size: number, screenWidth: number = 1920) {
  const clientWidth =
    window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  if (!clientWidth) return
  const fontSize = clientWidth / screenWidth // 尺寸大小
  return size * fontSize
}

/**
 * 更新配置项数据指定key的选项数据
 * @param list 配置项列表
 * @param key 需要设置数据的key
 * @param options 要设置的选项设局
 */
export function setOptions(list: any[], key: string, options: any[]) {
  list.forEach(item => {
    if (item.key === key) {
      item.options = options
    }
  })
}
